home *** CD-ROM | disk | FTP | other *** search
/ Clickx 115 / Clickx 115.iso / software / tools / windows / tails-i386-0.16.iso / live / filesystem.squashfs / usr / bin / lwp-download < prev    next >
Encoding:
Text File  |  2010-05-18  |  8.3 KB  |  332 lines

  1. #!/usr/bin/perl -w
  2.  
  3. eval 'exec /usr/bin/perl -w -S $0 ${1+"$@"}'
  4.     if 0; # not running under some shell
  5.  
  6. =head1 NAME
  7.  
  8. lwp-download - Fetch large files from the web
  9.  
  10. =head1 SYNOPSIS
  11.  
  12. B<lwp-download> [B<-a>] [B<-s>] <I<url>> [<I<local path>>]
  13.  
  14. =head1 DESCRIPTION
  15.  
  16. The B<lwp-download> program will save the file at I<url> to a local
  17. file.
  18.  
  19. If I<local path> is not specified, then the current directory is
  20. assumed.
  21.  
  22. If I<local path> is a directory, then the last segment of the path of the
  23. I<url> is appended to form a local filename.  If the I<url> path ends with
  24. slash the name "index" is used.  With the B<-s> option pick up the last segment
  25. of the filename from server provided sources like the Content-Disposition
  26. header or any redirect URLs.  A file extension to match the server reported
  27. Content-Type might also be appended.  If a file with the produced filename
  28. already exists, then B<lwp-download> will prompt before it overwrites and will
  29. fail if its standard input is not a terminal.  This form of invocation will
  30. also fail is no acceptable filename can be derived from the sources mentioned
  31. above.
  32.  
  33. If I<local path> is not a directory, then it is simply used as the
  34. path to save into.  If the file already exists it's overwritten.
  35.  
  36. The I<lwp-download> program is implemented using the I<libwww-perl>
  37. library.  It is better suited to down load big files than the
  38. I<lwp-request> program because it does not store the file in memory.
  39. Another benefit is that it will keep you updated about its progress
  40. and that you don't have much options to worry about.
  41.  
  42. Use the C<-a> option to save the file in text (ascii) mode.  Might
  43. make a difference on dosish systems.
  44.  
  45. =head1 EXAMPLE
  46.  
  47. Fetch the newest and greatest perl version:
  48.  
  49.  $ lwp-download http://www.perl.com/CPAN/src/latest.tar.gz
  50.  Saving to 'latest.tar.gz'...
  51.  11.4 MB received in 8 seconds (1.43 MB/sec)
  52.  
  53. =head1 AUTHOR
  54.  
  55. Gisle Aas <gisle@aas.no>
  56.  
  57. =cut
  58.  
  59. #' get emacs out of quote mode
  60.  
  61. use strict;
  62.  
  63. use LWP::UserAgent ();
  64. use LWP::MediaTypes qw(guess_media_type media_suffix);
  65. use URI ();
  66. use HTTP::Date ();
  67.  
  68. my $progname = $0;
  69. $progname =~ s,.*/,,;    # only basename left in progname
  70. $progname =~ s,.*\\,, if $^O eq "MSWin32";
  71. $progname =~ s/\.\w*$//; # strip extension if any
  72.  
  73. #parse option
  74. use Getopt::Std;
  75. my %opt;
  76. unless (getopts('as', \%opt)) {
  77.     usage();
  78. }
  79.  
  80. my $url = URI->new(shift || usage());
  81. my $argfile = shift;
  82. usage() if defined($argfile) && !length($argfile);
  83. my $VERSION = "5.835";
  84.  
  85. my $ua = LWP::UserAgent->new(
  86.    agent => "lwp-download/$VERSION ",
  87.    keep_alive => 1,
  88.    env_proxy => 1,
  89. );
  90.  
  91. my $file;      # name of file we download into
  92. my $length;    # total number of bytes to download
  93. my $flength;   # formatted length
  94. my $size = 0;  # number of bytes received
  95. my $start_t;   # start time of download
  96. my $last_dur;  # time of last callback
  97.  
  98. my $shown = 0; # have we called the show() function yet
  99.  
  100. $SIG{INT} = sub { die "Interrupted\n"; };
  101.  
  102. $| = 1;  # autoflush
  103.  
  104. my $res = $ua->request(HTTP::Request->new(GET => $url),
  105.   sub {
  106.       unless(defined $file) {
  107.       my $res = $_[1];
  108.  
  109.       my $directory;
  110.       if (defined $argfile && -d $argfile) {
  111.           ($directory, $argfile) = ($argfile, undef);
  112.       }
  113.  
  114.       unless (defined $argfile) {
  115.           # find a suitable name to use
  116.           $file = $opt{s} && $res->filename;
  117.  
  118.           # if this fails we try to make something from the URL
  119.           unless ($file) {
  120.           $file = ($url->path_segments)[-1];
  121.           if (!defined($file) || !length($file)) {
  122.               $file = "index";
  123.               my $suffix = media_suffix($res->content_type);
  124.               $file .= ".$suffix" if $suffix;
  125.           }
  126.           elsif ($url->scheme eq 'ftp' ||
  127.                $file =~ /\.t[bg]z$/   ||
  128.                $file =~ /\.tar(\.(Z|gz|bz2?))?$/
  129.               ) {
  130.               # leave the filename as it was
  131.           }
  132.           else {
  133.               my $ct = guess_media_type($file);
  134.               unless ($ct eq $res->content_type) {
  135.               # need a better suffix for this type
  136.               my $suffix = media_suffix($res->content_type);
  137.               $file .= ".$suffix" if $suffix;
  138.               }
  139.           }
  140.           }
  141.  
  142.           # validate that we don't have a harmful filename now.  The server
  143.           # might try to trick us into doing something bad.
  144.           if (!length($file) ||
  145.                   $file =~ s/([^a-zA-Z0-9_\.\-\+\~])/sprintf "\\x%02x", ord($1)/ge ||
  146.           $file =~ /^\./
  147.           )
  148.               {
  149.           die "Will not save <$url> as \"$file\".\nPlease override file name on the command line.\n";
  150.           }
  151.  
  152.           if (defined $directory) {
  153.               require File::Spec;
  154.               $file = File::Spec->catfile($directory, $file);
  155.           }
  156.  
  157.           # Check if the file is already present
  158.           if (-l $file) {
  159.           die "Will not save <$url> to link \"$file\".\nPlease override file name on the command line.\n";
  160.           }
  161.           elsif (-f _) {
  162.           die "Will not save <$url> as \"$file\" without verification.\nEither run from terminal or override file name on the command line.\n"
  163.               unless -t;
  164.           $shown = 1;
  165.           print "Overwrite $file? [y] ";
  166.           my $ans = <STDIN>;
  167.           unless (defined($ans) && $ans =~ /^y?\n/) {
  168.               if (defined $ans) {
  169.               print "Ok, aborting.\n";
  170.               }
  171.               else {
  172.               print "\nAborting.\n";
  173.               }
  174.               exit 1;
  175.           }
  176.           $shown = 0;
  177.           }
  178.           elsif (-e _) {
  179.           die "Will not save <$url> as \"$file\".  Path exists.\n";
  180.           }
  181.           else {
  182.           print "Saving to '$file'...\n";
  183.           use Fcntl qw(O_WRONLY O_EXCL O_CREAT);
  184.           sysopen(FILE, $file, O_WRONLY|O_EXCL|O_CREAT) ||
  185.               die "Can't open $file: $!";
  186.           }
  187.       }
  188.       else {
  189.           $file = $argfile;
  190.       }
  191.       unless (fileno(FILE)) {
  192.           open(FILE, ">", $file) || die "Can't open $file: $!\n";
  193.       }
  194.           binmode FILE unless $opt{a};
  195.       $length = $res->content_length;
  196.       $flength = fbytes($length) if defined $length;
  197.       $start_t = time;
  198.       $last_dur = 0;
  199.       }
  200.  
  201.       print FILE $_[0] or die "Can't write to $file: $!\n";
  202.       $size += length($_[0]);
  203.  
  204.       if (defined $length) {
  205.       my $dur  = time - $start_t;
  206.       if ($dur != $last_dur) {  # don't update too often
  207.           $last_dur = $dur;
  208.           my $perc = $size / $length;
  209.           my $speed;
  210.           $speed = fbytes($size/$dur) . "/sec" if $dur > 3;
  211.           my $secs_left = fduration($dur/$perc - $dur);
  212.           $perc = int($perc*100);
  213.           my $show = "$perc% of $flength";
  214.           $show .= " (at $speed, $secs_left remaining)" if $speed;
  215.           show($show, 1);
  216.       }
  217.       }
  218.       else {
  219.       show( fbytes($size) . " received");
  220.       }
  221.   }
  222. );
  223.  
  224. if (fileno(FILE)) {
  225.     close(FILE) || die "Can't write to $file: $!\n";
  226.  
  227.     show("");  # clear text
  228.     print "\r";
  229.     print fbytes($size);
  230.     print " of ", fbytes($length) if defined($length) && $length != $size;
  231.     print " received";
  232.     my $dur = time - $start_t;
  233.     if ($dur) {
  234.     my $speed = fbytes($size/$dur) . "/sec";
  235.     print " in ", fduration($dur), " ($speed)";
  236.     }
  237.     print "\n";
  238.  
  239.     if (my $mtime = $res->last_modified) {
  240.     utime time, $mtime, $file;
  241.     }
  242.  
  243.     if ($res->header("X-Died") || !$res->is_success) {
  244.     if (my $died = $res->header("X-Died")) {
  245.         print "$died\n";
  246.     }
  247.     if (-t) {
  248.         print "Transfer aborted.  Delete $file? [n] ";
  249.         my $ans = <STDIN>;
  250.         if (defined($ans) && $ans =~ /^y\n/) {
  251.         unlink($file) && print "Deleted.\n";
  252.         }
  253.         elsif ($length > $size) {
  254.         print "Truncated file kept: ", fbytes($length - $size), " missing\n";
  255.         }
  256.         else {
  257.         print "File kept.\n";
  258.         }
  259.             exit 1;
  260.     }
  261.     else {
  262.         print "Transfer aborted, $file kept\n";
  263.     }
  264.     }
  265.     exit 0;
  266. }
  267.  
  268. # Did not manage to create any file
  269. print "\n" if $shown;
  270. if (my $xdied = $res->header("X-Died")) {
  271.     print "$progname: Aborted\n$xdied\n";
  272. }
  273. else {
  274.     print "$progname: ", $res->status_line, "\n";
  275. }
  276. exit 1;
  277.  
  278.  
  279. sub fbytes
  280. {
  281.     my $n = int(shift);
  282.     if ($n >= 1024 * 1024) {
  283.     return sprintf "%.3g MB", $n / (1024.0 * 1024);
  284.     }
  285.     elsif ($n >= 1024) {
  286.     return sprintf "%.3g KB", $n / 1024.0;
  287.     }
  288.     else {
  289.     return "$n bytes";
  290.     }
  291. }
  292.  
  293. sub fduration
  294. {
  295.     use integer;
  296.     my $secs = int(shift);
  297.     my $hours = $secs / (60*60);
  298.     $secs -= $hours * 60*60;
  299.     my $mins = $secs / 60;
  300.     $secs %= 60;
  301.     if ($hours) {
  302.     return "$hours hours $mins minutes";
  303.     }
  304.     elsif ($mins >= 2) {
  305.     return "$mins minutes";
  306.     }
  307.     else {
  308.     $secs += $mins * 60;
  309.     return "$secs seconds";
  310.     }
  311. }
  312.  
  313.  
  314. BEGIN {
  315.     my @ani = qw(- \ | /);
  316.     my $ani = 0;
  317.  
  318.     sub show
  319.     {
  320.         my($mess, $show_ani) = @_;
  321.         print "\r$mess" . (" " x (75 - length $mess));
  322.     print $show_ani ? "$ani[$ani++]\b" : " ";
  323.         $ani %= @ani;
  324.         $shown++;
  325.     }
  326. }
  327.  
  328. sub usage
  329. {
  330.     die "Usage: $progname [-a] <url> [<lpath>]\n";
  331. }
  332.